package com.t.bricks.bussiness.controller.agent;

import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.t.bricks.bussiness.model.agent.AgentInfo;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.utils.function.json.JacksonShell;
import com.t.bricks.utils.function.url.HttpsUtil;
import com.t.bricks.utils.function.url.URLUtil;

/**
 * 代理转发服务控制器
 */
@RestController
@RequestMapping("/agent/")
public class AgentController {
	
	/**
	 * 访问本系统的密钥
	 */
	@Value("${app.key:配置文件没有配置app.key}")
	private String appKey;
	
	/**
	 * post请求转发
	 * @param data
	 * @return
	 */
	@RequestMapping(method={RequestMethod.POST}, value="/post")
	public MsgEmity post(@RequestBody AgentInfo agentInfo) {
		return doAgent(agentInfo);
	}
	
	/**
	 * get请求转发
	 * @param data
	 * @return
	 */
	@RequestMapping(method={RequestMethod.GET}, value="/get")
	public MsgEmity get(@RequestBody AgentInfo agentInfo) {
		return doAgent(agentInfo);
	}
	
	/**
	 * 执行转发动作
	 * @param data
	 * @return
	 */
	private MsgEmity doAgent(AgentInfo agentInfo) {
		if (null == agentInfo) {
			Log.debug("请求信息格式错误");
			return new MsgEmity(false, "请求信息格式错误", 9001);
		}
		
		if (null == agentInfo.getsId() || "".equals(agentInfo.getsId().trim())) {
			return new MsgEmity(false, "请求信息编号缺失", 9002);
		}
		
		String msg = agentInfo.valid();
		if (null != msg) {
			Log.debug(msg);
			return new MsgEmity(false, msg, 9003);
		}
		
		String url = agentInfo.getsUrl();
		if (url.indexOf("https://") == 0) {
			if ("GET".equalsIgnoreCase(agentInfo.getsMethodType())) {
				return HttpsUtil.get(url, agentInfo.getsParams());
			}
			
			return HttpsUtil.post(url, agentInfo.getsParams());
		}

		if ("POST".equalsIgnoreCase(agentInfo.getsMethodType())) {
			if (1 == agentInfo.getiJsonParam()) {
				return URLUtil.postJson(url, agentInfo.getsParams());
			}
			
			Map<String, Object> map = JacksonShell.toJavaObject(agentInfo.getsParams(), Map.class);
			return URLUtil.post(url, map);
		}
		
		if (1 != agentInfo.getiJsonParam() || null == agentInfo.getsParams() || "".equals(agentInfo.getsParams().trim())) {
			return URLUtil.get(url);
		}

		StringBuilder sb = new StringBuilder().append(url).append("?lt=12");
		Map<String, String> map = JacksonShell.toJavaObject(agentInfo.getsParams(), Map.class);
		if (null != map) {
			for (String name : map.keySet()) {
				sb.append("&").append(name).append("=").append(map.get(name));
			}
		}
		
		return URLUtil.get(sb.toString());
	}
	
}
